package me.panpf.sketch.sample.vt;

import me.panpf.sketch.sample.vt.adapter.VideoListAdapter;
import me.panpf.sketch.sample.vt.bean.VideoInfo;
import me.panpf.sketch.sample.vt.ui.listcontainer.BaseRefreshHeader;
import me.panpf.sketch.sample.vt.ui.listcontainer.RefreshListContainer;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.data.resultset.ResultSet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

/**
 * MainAbility
 *
 * @since : 2021/06/03
 */
public class MainAbility extends Ability {
    private static final String CUSTOM_REFRESH_TEXT = "Company Calling..";
    private static final String CUSTOM_PULL_DOWN_TEXT = "Loading Pull..";
    private static final int REFRESH = 100;
    private static final int LOAD_MORE = 200;
    private RefreshListContainer videoList;
    private Text statusText;
    private VideoListAdapter adapter;
    private ArrayList<VideoInfo> data = new ArrayList<>();
    private ArrayList<VideoInfo> videos;
    private int pageNum = 10; // 每页显示的条目数
    private int allPage;
    private int page = 1;
    private EventRunner eventRunner = EventRunner.getMainEventRunner();
    private MyHandler mHandler = new MyHandler(eventRunner);

    private class MyHandler extends EventHandler {
        private MyHandler(EventRunner runner) {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event.eventId == REFRESH) {
                mHandler.removeEvent(LOAD_MORE);
                hideTextAndLoading();
            } else {
                mHandler.removeEvent(REFRESH);
                setPageData();
            }
        }
    }

    public MainAbility() {
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        getWindow().setStatusBarColor(getColor(ResourceTable.Color_status_title));
        requestPermissions();
        currVideos = new ArrayList<>();
//        mEventHandler = new EventHandler(EventRunner.getMainEventRunner());
        initView();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        statusText.setText("Loading...");
        statusText.setVisibility(Component.VISIBLE);
        mHandler.sendEvent(REFRESH, 1000);

    }

    private ArrayList<VideoInfo> currVideos;

    private void setPageData() {
        if (currVideos != null) {
            currVideos.clear();
            int startP = (page - 1) * pageNum;
            for (int i = startP; i < page * pageNum; i++) {
                if (videos != null && i < videos.size()) {
                    currVideos.add(videos.get(i));
                } else {
                    break;
                }
            }
            if (page == 1) {
                adapter.setNewData(currVideos);
            } else {
                adapter.addData(currVideos);
            }
            if (videoList != null) {
                if (videoList.getDefaultRefreshHeaderView().getState() == BaseRefreshHeader.STATE_REFRESHING) {
                    videoList.refreshComplete();
                } else if (page == allPage) {
                    videoList.setNoMore(true);
                    adapter.notifyDataChanged();
                } else {
                    videoList.loadMoreComplete();
                    adapter.notifyDataChanged();
                }
            }
        }
    }

    private void hideTextAndLoading() {
        videos = findVideos();
        statusText.setVisibility(Component.HIDE);
        if (videos.size() == 0) {
            statusText.setText(getString(ResourceTable.String_no_videos));
            statusText.setVisibility(Component.VISIBLE);
            videoList.refreshComplete();
        } else {
            int startP = (page - 1) * pageNum;
            if (currVideos != null) {
                currVideos.clear();
                for (int i = startP; i < page * pageNum; i++) {
                    if (i < videos.size()) {
                        currVideos.add(videos.get(i));
                    }
                }
            }
            allPage = (int) Math.ceil(videos.size() * 1f / pageNum);
            if (page == 1) {
                adapter.setNewData(currVideos);
            } else {
                adapter.addData(currVideos);
            }
            videoList.refreshComplete();
            if (allPage == 1) {
                videoList.setNoMore(true);
            }
            adapter.notifyDataChanged();
        }
    }

    private void requestPermissions() {
        String[] permissions = {"ohos.permission.MICROPHONE",
                "ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(permissions, 0);
    }

    private void initView() {
        if (findComponentById(ResourceTable.Id_list_container) instanceof RefreshListContainer) {
            videoList = (RefreshListContainer) findComponentById(ResourceTable.Id_list_container);
        }
        videoList.getDefaultRefreshHeaderView().setRefreshTimeVisible(true);
        videoList.getDefaultRefreshHeaderView().setIndicatorColor(Color.RED.getValue());

        videoList.setArrowImageView(ResourceTable.Media_iconfont_downgrey);
        videoList.setLimitNumberToCallLoadMore(2);
        videoList.setLoadingListener(new RefreshListContainer.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                mHandler.sendEvent(REFRESH, 1500);
            }

            @Override
            public void onLoadMore() {
                if (page < allPage) {
                    page++;
                    mHandler.sendEvent(LOAD_MORE, 1000);
                }
            }
        });

        if (findComponentById(ResourceTable.Id_status_text) instanceof Text) {
            statusText = (Text) findComponentById(ResourceTable.Id_status_text);
        }
        adapter = new VideoListAdapter(this, data, ResourceTable.Layout_list_item_my_video);
        videoList.setItemProvider(adapter);
        videoList.setLongClickable(false);
        adapter.setOnItemClickListener(new RefreshListContainer.RecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Component component, int position) {
                VideoInfo videoInfo = data.get(position);
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                try {
                    intent.setUriAndType(Uri.parse(videoInfo.getPath()),
                            Files.probeContentType(new File(videoInfo.getPath()).toPath()));
                    intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
                    startAbility(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private ArrayList<VideoInfo> findVideos() {
        DataAbilityHelper helper = DataAbilityHelper.creator(this);
        ArrayList<VideoInfo> resultList = new ArrayList<>();
        try {
            ResultSet resultSet = helper
                    .query(AVStorage.Video.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
            if (resultSet != null) {
                int limit = 100;
                if (resultSet.getRowCount() < limit) {
                    limit = resultSet.getRowCount();
                }
                resultSet.goToLastRow();
                VideoInfo videoInfo;
                for (int i = 0; i < limit; i++) {
                    String path = resultSet.getString(resultSet
                            .getColumnIndexForName(AVStorage.Video.Media.DATA));
                    String mediaType = resultSet.getString(resultSet
                            .getColumnIndexForName(AVStorage.Video.Media.MIME_TYPE));
                    int contentUrl = resultSet.getInt(resultSet
                            .getColumnIndexForName(AVStorage.Video.Media.ID));
                    long duration = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Video.Media.DURATION));
                    long size = resultSet.getInt(resultSet.getColumnIndexForName(AVStorage.Video.Media.SIZE));
                    String title = resultSet.getString(resultSet.getColumnIndexForName(AVStorage.Video.Media.TITLE));
                    long date = resultSet.getInt(resultSet
                            .getColumnIndexForName(AVStorage.Images.Media.DATE_MODIFIED));
                    String fileName = resultSet.getString(resultSet
                            .getColumnIndexForName(AVStorage.Images.Media.DISPLAY_NAME));
                    videoInfo = new VideoInfo();
                    videoInfo.setTitle(title);
                    videoInfo.setMimeType(mediaType);
                    videoInfo.setDuration(duration);
                    videoInfo.setSize(size);
                    videoInfo.setDate(date);
                    videoInfo.setPath(path);
                    videoInfo.setId(contentUrl);
                    resultList.add(videoInfo);
                    resultSet.goToPreviousRow();
                }
                resultSet.close();
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return resultList;
    }
}
